package vikaa.versonservice;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import vikaa.tools.HttpUtil;
import vikaa.wowo.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;


public class VersonUpdate extends Activity{
    private ProgressDialog mProgressDialog;
    private ProgressDialog pd;
    private int FileLength; 
    private int DownedFileLength=0;  
    private String appUrl ;
    private String appName;
    private static  int           VerCode;
	private static  String           VerName;
	private  String           newVerCode;
	private  String           newVerName;
	private  String savePathString;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.verson_update);
        DownedFileLength=0;  
        VerCode = getVerCode(VersonUpdate.this); 
		VerName = getVerName(VersonUpdate.this);
        new UpdateThread().start();
        pd = new ProgressDialog(VersonUpdate.this);
		pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		pd.setMessage(getText(R.string.check_verson));
		pd.show();
	}
	public void initview(){
		mProgressDialog = new ProgressDialog(VersonUpdate.this);  
	    mProgressDialog.setIcon(R.drawable.icon);  
	    mProgressDialog.setTitle("新版本");  
	    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
	    mProgressDialog.show(); 
	}
	public static int getVerCode(Context context) {  
        int verCode = -1;  
        try {  
            verCode = context.getPackageManager().getPackageInfo(  
                    "com.vikaa.wowo", 0).versionCode;  
        } catch (NameNotFoundException e) {
        	e.printStackTrace();
        }  
        return verCode;  
    }  
    //get verson name from app
    public static String getVerName(Context context) {  
        String verName = "";  
        try {  
            verName = context.getPackageManager().getPackageInfo(  
                    "com.vikaa.wowo", 0).versionName;  
        } catch (NameNotFoundException e) {  
        	e.printStackTrace();
        }  
        return verName;     
    }
	//no update
    private void notNewVersionShow() { 
        StringBuffer sb = new StringBuffer();  
        sb.append("目前版本名字:");  
        sb.append(VerName);  
        sb.append(",版本号:");  
        sb.append(VerCode);  
        sb.append(",你的窝窝已是最新版本");  
        Dialog dialog = new AlertDialog.Builder(VersonUpdate.this).setTitle("提示")  
                .setMessage(sb.toString()) 
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,  
                                    int which) {  
                            	finish();
                            }  
                        }).create();
        dialog.show();  
    } 
    //update new verson
    private void doNewVersionUpdate() {  
    	//unregisterReceiver(vsbc);
        StringBuffer sb = new StringBuffer();  
        sb.append("目前版本名字");  
        sb.append(VerName);  
        sb.append("，版本号:");  
        sb.append(VerCode);  
        sb.append(",新版本名字:");  
        sb.append(newVerName);  
        sb.append("，版本号:");  
        sb.append(newVerCode);  
        sb.append(",需要更新新版本吗?");  
        Dialog dialog = new AlertDialog.Builder(VersonUpdate.this)  
                .setTitle("提示")  
                .setMessage(sb.toString())  
                .setPositiveButton("更新",
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,  
                                    int which) {  
                            	initview();
                            	new Thread(new Runnable() {
									public void run() {
                                    	downFile(appUrl); 
									}
								}).start();
                            }  
                        })  
                .setNegativeButton("下次再更新",  
                        new DialogInterface.OnClickListener() {  
                            public void onClick(DialogInterface dialog,  
                                    int whichButton) {  
                            	finish();
                            }  
                        }).create();
        dialog.show();  
    }  
	private Handler handler=new Handler()  
    {  
         public void handleMessage(Message msg)  
        {  
        if (!Thread.currentThread().isInterrupted()) {  
            switch (msg.what) {  
            case 0:  
                mProgressDialog.setMax(FileLength);
                break;  
            case 1:  
                int x=DownedFileLength*100/FileLength;  
                mProgressDialog.setProgress(DownedFileLength);
                break;  
            case 2:  
                mProgressDialog.dismiss();
                update();
                break;  
            case 3:
            	pd.dismiss();
            	doNewVersionUpdate();
            	break;
            case 4:
            	pd.dismiss();
            	notNewVersionShow();
            	break;
            case 5:
            	pd.dismiss();
				Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();
            	break;
            default:  
                break;  
            }  
        }     
        }  
    };
	public int downFile(String urlStr) {
		InputStream inputStream = null;
		try {
			OutputStream output = null;
			inputStream = getInputStreamFromUrl(urlStr);
			if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
				String savePAth=Environment.getExternalStorageDirectory()+"/vikaa";  
		        File file1=new File(savePAth);  
		        if (!file1.exists()) {  
		            file1.mkdir();  
		        }  
		        savePathString=Environment.getExternalStorageDirectory()+"/vikaa/"+appName+".apk";  
		        File file =new File(savePathString);  
		        if (!file.exists()) {  
		            try {  
		                file.createNewFile();  
		            } catch (IOException e) {  
		                // TODO Auto-generated catch block  
		                e.printStackTrace();  
		            }     
		        }
				output = new FileOutputStream(file);
				Message message=new Message();
	            message.what=0;  
	            handler.sendMessage(message);
				byte buffer[] = new byte[4 * 1024];
				int temp;
				while ((temp = inputStream.read(buffer)) != -1) {
					output.write(buffer, 0, temp);
					DownedFileLength += temp;  
	                Message message1=new Message();  
	                message1.what=1;  
	                handler.sendMessage(message1);
				}
				output.flush();
				Message message2=new Message();  
	            message2.what=2;  
	            handler.sendMessage(message2);  
            }
			else{
		        savePathString = getApplicationInfo().dataDir +"/"+appName +".apk"; 
		        File file =new File(savePathString);  
		        if (!file.exists()) {  
		            try {  
		                file.createNewFile();  
		            } catch (IOException e) {  
		                // TODO Auto-generated catch block  
		                e.printStackTrace();  
		            }     
		        }
				output = new FileOutputStream(file);
				Message message=new Message();
	            message.what=0;  
	            handler.sendMessage(message);
				byte buffer[] = new byte[4 * 1024];
				int temp;
				while ((temp = inputStream.read(buffer)) != -1) {
					output.write(buffer, 0, temp);
					DownedFileLength += temp;  
	                Message message1=new Message();  
	                message1.what=1;  
	                handler.sendMessage(message1);
				}
				output.flush();
				Message message2=new Message();  
	            message2.what=2;  
	            handler.sendMessage(message2);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		} finally {
			try {
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return 0;
	}
	public InputStream getInputStreamFromUrl(String urlStr)
			throws MalformedURLException, IOException {
		URL url = new URL(urlStr);
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		InputStream inputStream = urlConn.getInputStream();
		FileLength=urlConn.getContentLength();
		return inputStream;
	}
	public void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(savePathString)),
                        "application/vnd.android.package-archive");
        startActivity(intent);
    }
	public class UpdateThread extends Thread{
		private boolean isrun = true;
		@Override
		public void run() {
			while(isrun){
				Map<String, String> map = new HashMap<String, String>();
				map.put("os_verson", android.os.Build.VERSION.RELEASE);
				try {
					isrun = false;
		        	String url = HttpUtil.BASE_URL + "corel/apkupdate";
		            JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
		            String result = jsonObj.getString("result");
		            if (result.equals("1")) {  
	                    newVerCode = jsonObj.getJSONObject("info").getString("verCode");  
	                    newVerName = jsonObj.getJSONObject("info").getString("verName");  
	                    appName = jsonObj.getJSONObject("info").getString("appName");  
	                    appUrl = jsonObj.getJSONObject("info").getString("appUrl"); 
	                    if(Integer.valueOf(newVerCode)>VerCode){
		                    Message msg = new Message();
		                    msg.what = 3;
		                    handler.sendMessage(msg);
	                    }
	                    else{
			            	Message msg = new Message();
		                    msg.what = 4;
		                    handler.sendMessage(msg);
	                    }
		            } 
		            else if(result.equals("0")){
		            	Message msg = handler.obtainMessage(5);
						msg.obj = jsonObj.getString("msg");
						handler.sendMessage(msg);
		            }
		            else{
		            	String error = jsonObj.getJSONObject("info").getString("error");
						Message msg = handler.obtainMessage(5);
						msg.obj = error;
						handler.sendMessage(msg);
		            }
				} catch (Exception e) {
					isrun = false;
					e.printStackTrace();
				}  
			}
		}
	}
}
